<?php

class FileController extends BaseController {
	
	/**
     * 上传用户图片
	 */
	public function uploadUserImage()
	{
        // upload avatar
        $rules = array(
        	'user_id' => 'required|exists:user,id',
            'upload_file' => 'required'
        );
        $messages = array(
            'user_id.exists' => '这个用户不存在',
            'upload_file.required' => '请上传图片',
        );

        $posts = Input::all();
        $validator = Validator::make ( $posts, $rules, $messages );
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView(
                'errors.400', 
                $validator->errors(),
                400
            );
        }

        $avatar_folder = Config::get('app.upload_dir') . '/user_img/' . $posts['user_id'];
        $upload_folder = UploadHelper::getFileFolder($avatar_folder);

        try {
            $upload_result  = UploadHelper::uploadImage('upload_file', $upload_folder);
            if ($upload_result['error'] == 0) {
            } else {
            	throw new Exception('上传图片失败。');
            }
        } catch(Exception $ex) {
            Log::error($ex);
            return $this->makeView(
                'errors.503', 
                '上传图片失败，请稍后再试。',
                503
            );
        }

        $file_path = $avatar_folder . "/" . $upload_result['files'][0]['basename'] . "." . $upload_result['files'][0]['ext'];
        $file_url = route('file.show_image') . "?path=" . $file_path;

        return $this->makeView(
            'general.200', 
            array('file_path' => $file_path, 'file_url' => $file_url),
            200
        );
	}


    public function uploadFile()
    {
        // upload avatar
        $rules = array(
            'upload_file' => 'required'
        );
        $messages = array(
            'upload_file.required' => '请上传图片'
        );

        $posts = Input::all();
        if (isset($posts['user_id'])) {
            $rules['user_id'] = 'exists:user,id';
            $messages['user_id.exists'] = '这个用户不存在';
        }

        $validator = Validator::make ( $posts, $rules, $messages );
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView(
                'errors.400', 
                $validator->errors(),
                400
            );
        }

        if (isset($posts['user_id'])) {
            $upload_folder = Config::get('app.upload_dir').'/user_file/'.$posts['user_id'];
        } else {
            $upload_folder = Config::get('app.upload_dir').'/question_file';
        }

        try {
            $allow_exts = ['jpg','jpeg','jpe','png','gif','bmp','doc','pdf'];
            $save_folder = UploadHelper::getFileFolder($upload_folder);
            $upload_result  = UploadHelper::upload('upload_file', $save_folder, $allow_exts);
            if ($upload_result['error'] == 0) {
            } else {
                throw new Exception('上传文件失败。');
            }
        } catch(Exception $ex) {
            Log::error($ex);
            return $this->makeView(
                'errors.503', 
                '上传图片失败，请稍后再试。',
                503
            );
        }
        $file_path = $upload_folder ."/" . $upload_result['files'][0]['basename'] . "." . $upload_result['files'][0]['ext'];
        return $this->makeView(
            'general.200', 
            array('file_path' => $file_path),
            200
        );
    }

    /**
     * 通过文件的路径下载文件
     */
    public function downloadFile()
    {
        $upload_root = Config::get('app.upload_root');
        $path = Input::get('path');
        $downloadfile = $upload_root . $path;
        $pathToFile = chop(public_path(),'/') . '/' . $downloadfile;
        return Response::download($pathToFile);
    }

    /**
     * 通过文件的id下载文件
     */
    public function download($id)
    {
        $attachment = FileAttachment::find($id);
        switch($attachment->item_type) {
            case FileAttachment::ITEM_TYPE_ARTICLE:
                $article = Article::find($attachment->item_id);
                $article->downs = $article->downs + 1;
                $article->save();
                break;
            case FileAttachment::ITEM_TYPE_POST:
                break;
        }
        $upload_root = Config::get('app.upload_root');
        $path = $attachment->src;
        $downloadfile = $upload_root . $path;
        $pathToFile = chop(public_path(),'/') . '/' . $downloadfile;
        return Response::download($pathToFile, $attachment->file_name);
    }

    public function showImage()
    {
        $upload_root = Config::get('app.upload_root');
        $path = Input::get('path');
        $uploadfile = $upload_root . $path;
        if (file_exists($uploadfile)) {
            $mime_type = mime_content_type($uploadfile);
            if ($this->isAllowedMimeType($mime_type)) {
                return Response::make(File::get($uploadfile), 200, array('content-type' => $mime_type));
            }
        }
        return Response::view('errors.404', array(), 404);
    }

    private function isAllowedMimeType($mime_type) {
        $allowed_extensions = ['jpg','jpeg','jpe','png','gif','bmp'];
        foreach($allowed_extensions as $extension) {
            if ($mime_type == "image/" . $extension) {
                return true;
            }
        }
        return false;
    }
}
